<script setup lang="ts">
import { Utils } from '@/common/utils.js'
import { INJECT_THEME_COLOR } from '@/common/provideType'

// 主题颜色
const THEME_COLOR = inject(INJECT_THEME_COLOR)!
const addEvent = ref()
// 视口高度
const dom = document
const goTopStatus = ref<boolean>(false)

const goTopFn = () => {
	const timer = setInterval(function () {
		let scrollTop = dom.documentElement.scrollTop || dom.body.scrollTop
		let scrollSpeed = Math.floor(-scrollTop / 5)
		dom.documentElement.scrollTop = dom.body.scrollTop = scrollTop + scrollSpeed
		if (scrollTop <= 0) {
			clearInterval(timer)
		}
	}, 30)
}

onMounted(() => {
	addEvent.value = Utils.throttle(() => {
		// 滚动条滚动的高度
		let scrollTop = dom.documentElement.scrollTop || dom.body.scrollTop
		goTopStatus.value = scrollTop >= 100 ? true : false
	}, 50)
	
	window.addEventListener('scroll', addEvent.value)
})
</script>

<template>
    <span v-show="goTopStatus" :class="[`back-to-top-icon bg-${THEME_COLOR}`]" @click="goTopFn">返回顶部</span>
</template>

<style lang="scss" scoped>
    .back-to-top-icon{
        width: .4rem;
        height: 1rem;
        line-height: .4rem;
        text-align: center;
        cursor: pointer;
        writing-mode:vertical-lr;
        font-size: .14rem;
        letter-spacing: .03rem;
        color: $color-white;
        border-radius: .2rem;
        position: fixed;
        right: .15rem;
        bottom: .2rem;
        z-index: 8888;
    }
</style>